import React, { useState } from 'react'
import { Player, Match, LeagueSearchResult, LeagueDetail, LeagueMatch } from './types/dota'
import { openDotaAPI } from './services/api'
import { ThemeProvider } from './contexts/ThemeContext'
import { ApiKeyProvider } from './contexts/ApiKeyContext'
import { ToastProvider } from './components/ui/toast'
import { ErrorBoundary } from './components/ui/error-boundary'
import { AppSidebar } from './components/app-sidebar'
import { ThemeToggle } from './components/theme-toggle'
import SearchPlayer from './components/SearchPlayer'
import PlayerProfile from './components/PlayerProfile'
import PlayerSearchResults from './components/PlayerSearchResults'
import PlayerMatchDetail from './components/PlayerMatchDetail'
import LeagueMatchDetail from './components/LeagueMatchDetail'
import LeagueSearch from './components/LeagueSearch'
import LeagueInfo from './components/LeagueInfo'
import LeagueMatches from './components/LeagueMatches'
import LeagueRankings from './components/LeagueRankings'
import Settings from './components/Settings'
import {
  SidebarInset,
  SidebarProvider,
  SidebarTrigger,
} from "@/components/ui/sidebar"
import { Separator } from "@/components/ui/separator"
import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbLink,
  BreadcrumbList,
  BreadcrumbPage,
  BreadcrumbSeparator,
} from "@/components/ui/breadcrumb"
import './App.css'

function App() {
  const [player, setPlayer] = useState<Player | null>(null)
  const [matches, setMatches] = useState<Match[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [searchResults, setSearchResults] = useState<any[]>([])
  const [showSearchResults, setShowSearchResults] = useState(false)
  const [currentView, setCurrentView] = useState<'search' | 'player' | 'player-match' | 'league' | 'league-info' | 'league-matches' | 'league-match' | 'league-rankings' | 'settings'>('search')
  const [selectedMatchId, setSelectedMatchId] = useState<string | null>(null)
  
  // 联赛相关状态
  const [selectedLeague, setSelectedLeague] = useState<LeagueDetail | null>(null)
  const [leagueMatches, setLeagueMatches] = useState<LeagueMatch[]>([])
  const [currentLeagueId, setCurrentLeagueId] = useState<number | null>(null)
  
  // 联赛数据缓存 - 按联赛ID存储比赛数据
  const [leagueDataCache, setLeagueDataCache] = useState<Map<number, {
    matches: LeagueMatch[]
    detail: LeagueDetail | null
    lastUpdated: number
  }>>(new Map())
  
  // 导航历史状态 - 每个tab独立的导航历史
  const [navigationHistory, setNavigationHistory] = useState<Array<{
    view: string
    title: string
    data?: any
  }>>([])

  // 获取当前tab的根视图和标题
  const getCurrentTabRoot = (view: string) => {
    if (view === 'search' || view === 'player' || view === 'player-match') {
      return { view: 'search', title: '玩家搜索' }
    } else if (view === 'league' || view === 'league-info' || view === 'league-matches' || view === 'league-match' || view === 'league-rankings') {
      return { view: 'league', title: '联赛搜索' }
    }
    return { view: 'search', title: '玩家搜索' }
  }

  // 重置导航历史到当前tab的根视图
  const resetNavigationToTabRoot = (view: string) => {
    const root = getCurrentTabRoot(view)
    setNavigationHistory([root])
  }

  // 导航历史管理函数
  const addToNavigationHistory = (view: string, title: string, data?: any) => {
    const currentRoot = getCurrentTabRoot(view)
    const newRoot = getCurrentTabRoot(navigationHistory[0]?.view || 'search')
    
    // 如果切换到不同的tab，重置导航历史
    if (currentRoot.view !== newRoot.view) {
      setNavigationHistory([currentRoot, { view, title, data }])
    } else {
      setNavigationHistory(prev => [...prev, { view, title, data }])
    }
  }

  const navigateToHistoryItem = (index: number) => {
    const targetItem = navigationHistory[index]
    if (!targetItem) return

    // 截取到目标位置的历史记录
    setNavigationHistory(prev => prev.slice(0, index + 1))
    
    // 根据目标视图设置相应的状态
    setCurrentView(targetItem.view as any)
    
    if (targetItem.view === 'search') {
      setPlayer(null)
      setMatches([])
      setSelectedMatchId(null)
      setSelectedLeague(null)
      setLeagueMatches([])
      setCurrentLeagueId(null)
      setError(null)
    } else if (targetItem.view === 'player' && targetItem.data) {
      setPlayer(targetItem.data.player)
      setMatches(targetItem.data.matches || [])
      setSelectedMatchId(null)
    } else if (targetItem.view === 'league') {
      setSelectedLeague(null)
      setLeagueMatches([])
      setCurrentLeagueId(null)
      setPlayer(null)
      setMatches([])
      setSelectedMatchId(null)
    } else if (targetItem.view === 'league-info' && targetItem.data) {
      setCurrentLeagueId(targetItem.data.leagueId)
      setSelectedLeague(targetItem.data.league)
    } else if (targetItem.view === 'league-matches' && targetItem.data) {
      setCurrentLeagueId(targetItem.data.leagueId)
    } else if (targetItem.view === 'league-rankings' && targetItem.data) {
      setCurrentLeagueId(targetItem.data.leagueId)
      setSelectedLeague(targetItem.data.league)
    }
  }

  const handleSearch = async (input: string) => {
    if (!input.trim()) return

    // 确保在玩家搜索tab中，初始化导航历史
    if (navigationHistory.length === 0 || getCurrentTabRoot(navigationHistory[0]?.view || 'search').view !== 'search') {
      resetNavigationToTabRoot('search')
    }

    setLoading(true)
    setError(null)
    setPlayer(null)
    setMatches([])
    setSearchResults([])
    setShowSearchResults(false)

    try {
      let accountId: string

      // 如果输入不是纯数字，尝试搜索用户名
      if (!/^\d+$/.test(input)) {
        const searchResults = await openDotaAPI.searchPlayers(input)
        if (searchResults.length === 0) {
          throw new Error('未找到该用户名对应的玩家')
        }
        
        // 如果找到多个玩家，显示选择列表
        if (searchResults.length > 1) {
          setSearchResults(searchResults)
          setShowSearchResults(true)
          setLoading(false)
          return
        }
        
        accountId = searchResults[0].account_id.toString()
      } else if (input.length === 17) {
        // Steam ID64 转换为 Account ID
        const steamId64 = BigInt(input)
        const accountIdBigInt = steamId64 - BigInt('76561197960265728')
        accountId = accountIdBigInt.toString()
      } else {
        // 直接使用 Account ID
        accountId = input
      }

      const playerData = await openDotaAPI.getPlayer(accountId)
      setPlayer(playerData)
      setCurrentView('player')
      
      // 添加到导航历史
      addToNavigationHistory('player', `玩家: ${playerData.profile?.personaname || '未知玩家'}`, { 
        player: playerData, 
        matches: [] 
      })
      
      // 自动加载比赛数据
      await handleLoadMatches(accountId)
    } catch (err) {
      setError(err instanceof Error ? err.message : '获取玩家信息失败')
    } finally {
      setLoading(false)
    }
  }

  const handlePlayerSelect = async (selectedPlayer: any) => {
    console.log('App - handlePlayerSelect called with:', selectedPlayer)
    
    setLoading(true)
    setError(null)
    setShowSearchResults(false)
    setSearchResults([])

    try {
      const accountId = selectedPlayer.account_id.toString()
      console.log('App - fetching player data for account_id:', accountId)
      
      const playerData = await openDotaAPI.getPlayer(accountId)
      console.log('App - received player data:', playerData)
      
      setPlayer(playerData)
      setCurrentView('player')
      
      // 添加到导航历史
      addToNavigationHistory('player', `玩家: ${playerData.profile?.personaname || '未知玩家'}`, { 
        player: playerData, 
        matches: [] 
      })
      
      // 自动加载比赛数据
      await handleLoadMatches(accountId)
    } catch (err) {
      console.error('App - error in handlePlayerSelect:', err)
      setError(err instanceof Error ? err.message : '获取玩家信息失败')
    } finally {
      setLoading(false)
    }
  }

  const handleLoadMatches = async (accountId: string) => {
    try {
      const matchData = await openDotaAPI.getPlayerMatches(accountId)
      setMatches(matchData.slice(0, 10)) // 只显示最近10场比赛
    } catch (err) {
      setError('获取比赛记录失败')
    }
  }

  const handleMatchClick = (matchId: number) => {
    setSelectedMatchId(matchId.toString())
    
    // 根据当前视图确定比赛详情的类型
    if (currentView === 'league-matches') {
      setCurrentView('league-match')
      // 添加到导航历史
      addToNavigationHistory('league-match', `联赛比赛详情: ${matchId}`, { matchId: matchId.toString() })
    } else {
      setCurrentView('player-match')
      // 添加到导航历史
      addToNavigationHistory('player-match', `比赛详情: ${matchId}`, { matchId: matchId.toString() })
    }
  }

  const handleBackToPlayer = () => {
    // 通过导航历史返回到玩家页面
    const playerHistoryIndex = navigationHistory.findIndex(item => item.view === 'player')
    if (playerHistoryIndex !== -1) {
      navigateToHistoryItem(playerHistoryIndex)
    } else {
      // 如果历史中没有玩家页面，使用原来的逻辑
      setCurrentView('player')
      setSelectedMatchId(null)
    }
  }

  const handleBackToSearch = () => {
    // 重置到玩家搜索页面并重置导航历史
    resetNavigationToTabRoot('search')
    setCurrentView('search')
    setPlayer(null)
    setMatches([])
    setSelectedMatchId(null)
    setError(null)
    // 清理联赛相关状态
    setSelectedLeague(null)
    setLeagueMatches([])
    setCurrentLeagueId(null)
  }

  // 联赛相关处理函数
  const handleLeagueSelect = (league: LeagueSearchResult) => {
    setCurrentLeagueId(league.leagueid)
    setCurrentView('league-info')
    
    // 添加到导航历史
    addToNavigationHistory('league-info', `联赛: ${league.name}`, { 
      leagueId: league.leagueid, 
      league: league 
    })
  }

  const handleViewLeagueMatches = (leagueId: number) => {
    setCurrentLeagueId(leagueId)
    setCurrentView('league-matches')
    
    // 添加到导航历史
    addToNavigationHistory('league-matches', '联赛比赛', { leagueId })
  }

  // 处理联赛数据加载完成
  const handleLeagueDataLoaded = (leagueId: number, data: { matches: LeagueMatch[], detail: LeagueDetail }) => {
    setLeagueDataCache(prev => {
      const newCache = new Map(prev)
      newCache.set(leagueId, {
        matches: data.matches,
        detail: data.detail,
        lastUpdated: Date.now()
      })
      return newCache
    })
  }

  const handleViewLeagueRankings = (leagueId: number, leagueName: string) => {
    setCurrentLeagueId(leagueId)
    setCurrentView('league-rankings')
    
    // 设置selectedLeague，如果当前没有或ID不匹配，创建一个基本的LeagueDetail对象
    const leagueDetail = {
      leagueid: leagueId,
      name: leagueName,
      banner: '',
      tier: '',
      region: '',
      start_time: 0,
      end_time: 0,
      prize_pool: 0,
      organizer: '',
      description: '',
      stats: {
        teamCount: 0,
        matchCount: 0
      }
    }
    
    if (!selectedLeague || selectedLeague.leagueid !== leagueId) {
      setSelectedLeague(leagueDetail)
    }
    
    addToNavigationHistory('league-rankings', `联赛排行榜: ${leagueName}`, { 
      leagueId, 
      league: leagueDetail 
    })
  }

  const handleBackToLeagueSearch = () => {
    // 通过导航历史返回到联赛搜索页面
    const leagueSearchIndex = navigationHistory.findIndex(item => item.view === 'league')
    if (leagueSearchIndex !== -1) {
      navigateToHistoryItem(leagueSearchIndex)
    } else {
      // 如果历史中没有联赛搜索页面，使用原来的逻辑
      setCurrentView('league')
      setSelectedLeague(null)
      setLeagueMatches([])
      setCurrentLeagueId(null)
    }
  }

  const handleBackToLeagueInfo = () => {
    // 通过导航历史返回到联赛信息页面
    const leagueInfoIndex = navigationHistory.findIndex(item => item.view === 'league-info')
    if (leagueInfoIndex !== -1) {
      navigateToHistoryItem(leagueInfoIndex)
    } else {
      // 如果历史中没有联赛信息页面，使用原来的逻辑
      setCurrentView('league-info')
      setLeagueMatches([])
    }
  }

  const handleBackToLeagueMatches = () => {
    // 通过导航历史返回到联赛比赛列表页面
    const leagueMatchesIndex = navigationHistory.findIndex(item => item.view === 'league-matches')
    if (leagueMatchesIndex !== -1) {
      navigateToHistoryItem(leagueMatchesIndex)
    } else {
      // 如果历史中没有联赛比赛列表页面，使用原来的逻辑
      setCurrentView('league-matches')
      setSelectedMatchId(null)
    }
  }

  const handleBackToLeagueInfoFromRankings = () => {
    // 通过导航历史返回到联赛信息页面
    const leagueInfoIndex = navigationHistory.findIndex(item => item.view === 'league-info')
    if (leagueInfoIndex !== -1) {
      navigateToHistoryItem(leagueInfoIndex)
    } else {
      // 如果历史中没有联赛信息页面，使用原来的逻辑
      setCurrentView('league-info')
    }
  }

  // 处理侧边栏菜单点击
  const handleMenuClick = (view: string) => {
    if (view === 'search') {
      handleBackToSearch()
    } else if (view === 'league') {
      // 重置到联赛搜索页面并初始化导航历史
      resetNavigationToTabRoot('league')
      setCurrentView('league')
      // 清理其他状态
      setPlayer(null)
      setMatches([])
      setSelectedMatchId(null)
      setError(null)
    } else if (view === 'settings') {
      // 切换到设置页面
      setCurrentView('settings')
      setNavigationHistory([{ view: 'settings', title: '设置' }])
      // 清理其他状态
      setPlayer(null)
      setMatches([])
      setSelectedMatchId(null)
      setSelectedLeague(null)
      setLeagueMatches([])
      setCurrentLeagueId(null)
      setError(null)
    }
    // 其他菜单项可以在这里添加处理逻辑
  }



  return (
    <ToastProvider>
      <ThemeProvider>
        <ApiKeyProvider>
      <SidebarProvider>
        <AppSidebar onMenuClick={handleMenuClick} />
        <SidebarInset>
          <header className="flex h-16 shrink-0 items-center gap-2 transition-[width,height] ease-linear group-has-[[data-collapsible=icon]]/sidebar-wrapper:h-12">
            <div className="flex items-center gap-2 px-4">
              <SidebarTrigger className="-ml-1" />
              <Separator orientation="vertical" className="mr-2 h-4" />
              <Breadcrumb>
                <BreadcrumbList>
                  {navigationHistory.length > 0 && (
                    <>
                      {navigationHistory.map((item, index) => (
                        <React.Fragment key={index}>
                          {index > 0 && <BreadcrumbSeparator />}
                          <BreadcrumbItem>
                            {index === navigationHistory.length - 1 ? (
                              <BreadcrumbPage>{item.title}</BreadcrumbPage>
                            ) : (
                              <BreadcrumbLink 
                                href="#" 
                                onClick={() => navigateToHistoryItem(index)}
                              >
                                {item.title}
                              </BreadcrumbLink>
                            )}
                          </BreadcrumbItem>
                        </React.Fragment>
                      ))}
                    </>
                  )}
                </BreadcrumbList>
              </Breadcrumb>
            </div>
            <div className="ml-auto px-4">
              <ThemeToggle />
            </div>
          </header>
          
          <div className="flex flex-1 flex-col gap-4 p-4 pt-0">
            {/* <div className="grid auto-rows-min gap-4 md:grid-cols-3">
              <div className="aspect-video rounded-xl bg-muted/50" />
              <div className="aspect-video rounded-xl bg-muted/50" />
              <div className="aspect-video rounded-xl bg-muted/50" />
            </div> */}
            <div className="min-h-[100vh] flex-1 rounded-xl bg-muted/50 md:min-h-min p-4">
              {/* 根据当前视图显示不同内容 */}
              <ErrorBoundary>
                {currentView === 'search' && (
                <div className="flex items-center justify-center min-h-[60vh]">
                  <div className="w-full max-w-2xl">
                    {!showSearchResults ? (
                      <>
                        <SearchPlayer onSearch={handleSearch} loading={loading} />
                        
                        {/* 错误提示 */}
                        {error && (
                          <div className="mt-6">
                            <div className="modern-card border-destructive/50 bg-destructive/5">
                              <div className="p-6 text-center">
                                <div className="text-4xl mb-4">⚠️</div>
                                <div className="text-lg font-medium text-destructive mb-2">
                                  查询失败
                                </div>
                                <div className="text-sm text-muted-foreground">
                                  {error}
                                </div>
                              </div>
                            </div>
                          </div>
                        )}

                        {/* 加载状态 */}
                        {loading && (
                          <div className="mt-6">
                            <div className="modern-card">
                              <div className="p-8 text-center">
                                <div className="loading-spinner w-8 h-8 mx-auto mb-4"></div>
                                <div className="text-lg font-medium text-foreground">
                                  正在查询玩家信息...
                                </div>
                                <div className="text-sm text-muted-foreground mt-2">
                                  请稍候片刻
                                </div>
                              </div>
                            </div>
                          </div>
                        )}
                      </>
                    ) : (
                      <PlayerSearchResults
                        results={searchResults}
                        onPlayerSelect={handlePlayerSelect}
                        onBack={() => {
                          setShowSearchResults(false)
                          setSearchResults([])
                        }}
                      />
                    )}
                  </div>
                </div>
              )}

              {/* 玩家信息视图 */}
              {currentView === 'player' && player && (
                <div className="max-w-6xl mx-auto">
                  <PlayerProfile 
                    player={player} 
                    matches={matches}
                    onLoadMatches={handleLoadMatches}
                    onMatchClick={handleMatchClick}
                    onBackToSearch={handleBackToSearch}
                  />
                </div>
              )}

              {/* 玩家比赛详情视图 */}
              {currentView === 'player-match' && selectedMatchId && (
                <div className="max-w-6xl mx-auto">
                  <PlayerMatchDetail 
                    matchId={selectedMatchId}
                    onBack={handleBackToPlayer}
                  />
                </div>
              )}

              {/* 联赛搜索视图 */}
              {currentView === 'league' && (
                <div className="max-w-6xl mx-auto">
                  <LeagueSearch 
                    onLeagueSelect={handleLeagueSelect}
                  />
                </div>
              )}

              {/* 联赛信息视图 */}
              {currentView === 'league-info' && currentLeagueId && (
                <div className="max-w-6xl mx-auto">
                  <LeagueInfo 
                    leagueId={currentLeagueId}
                    onBack={handleBackToLeagueSearch}
                    onViewMatches={handleViewLeagueMatches}
                    onViewRankings={handleViewLeagueRankings}
                    onDataLoaded={handleLeagueDataLoaded}
                  />
                </div>
              )}

              {/* 联赛比赛列表视图 */}
              {currentView === 'league-matches' && currentLeagueId && (
                <div className="max-w-6xl mx-auto">
                  <LeagueMatches 
                    leagueId={currentLeagueId}
                    onBack={handleBackToLeagueInfo}
                    onMatchClick={handleMatchClick}
                  />
                </div>
              )}

              {/* 联赛比赛详情视图 */}
              {currentView === 'league-match' && selectedMatchId && (
                <div className="max-w-6xl mx-auto">
                  <LeagueMatchDetail 
                    matchId={selectedMatchId}
                    onBack={handleBackToLeagueMatches}
                  />
                </div>
              )}

              {/* 联赛排行榜视图 */}
              {currentView === 'league-rankings' && currentLeagueId && selectedLeague && (
                <div className="max-w-6xl mx-auto">
                  <LeagueRankings 
                    leagueId={currentLeagueId}
                    leagueName={selectedLeague.name}
                    onBack={handleBackToLeagueInfoFromRankings}
                    cachedMatches={leagueDataCache.get(currentLeagueId)?.matches || leagueMatches}
                    cachedLeagueDetail={leagueDataCache.get(currentLeagueId)?.detail || undefined}
                  />
                </div>
              )}

              {/* 设置页面视图 */}
              {currentView === 'settings' && (
                <div className="max-w-4xl mx-auto">
                  <Settings />
                </div>
              )}
              </ErrorBoundary>
            </div>
          </div>
        </SidebarInset>
      </SidebarProvider>
        </ApiKeyProvider>
      </ThemeProvider>
    </ToastProvider>
  )
}

export default App
